<?php

/**
 * Blog AR
 * 
 * Blog has Entry, Entry has Labels
 * 
 * @author David Monllaó <david.monllao@gmail.com>
 */
class Blog extends ActiveRecordSystem {

	/**
	 * Raw html
	 * @var string
	 */
    private $code;

    public function __construct($id = false, $name = false, $url = false) {

    	parent::__construct();
    	
        $this->tablename = 'blogs';

        if ($id) {
            $this->dbobj->id = $id;
        }
        if ($name) {
            $this->dbobj->name = $name;
        }
        if ($url) {
            $this->dbobj->url = $url;
        }

    }


    /**
     * Sends a curl petition
     */
    public function getBlogHtml($url) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,15);
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');

        $code = curl_exec($ch);
        $error = curl_errno($ch);
        curl_close($ch);

        if (!empty($error)) {
            return false;
        }

        $this->code = $code;

        return true;
    }


    /**
     * Stores the blog entries into DB
     * 
     * Only entries with labels will be added
     */
    public function getEntries() {
        
        // An array to reduce the DB queries
        $bloglabels = array();
        
        $this->domClean();
    
        $entries = $this->explodeEntries();


        foreach ($entries as $entrycode) {

            $entry = new Entry();
            $entry->getEntryData($entrycode);
            
            if (empty($entry->dbobj->title)) {
                continue;
            }
            
            // If there aren't labels we skip it
            if (empty($entry->labels)) {
            	continue;
            }
            
            // If it's almost empty
            if (substr_count($entry->dbobj->contenttoshow, ' ') < 50) {
            	continue;
            }
            
            // Check aready created entries
            if (entryExists($entry->dbobj->title, $entry->dbobj->url)) {
            	continue;
            }
            
            $entry->dbobj->timeadded = time();
            $entry->dbobj->id = $entry->insert();

            // If has been inserted into DB -> store labels
            if (!empty($entry->dbobj->id)) {
                $labels = $entry->saveLabels($bloglabels);
            }
        }
    }


    /**
     * Gets the blog locale
     */
    public function getLocale() {

        $pattern = '/\'locale\': \'(.*?)\',/';
        preg_match($pattern, $this->code, $matches);
        
        if (!empty($matches)) {
            return $matches[1];
        }
        
        return 'en-US';
    }


    /**
     * Stores into DB the blogspot links of the blog
     */
    public function saveBlogsLinks() {

        $now = time();
        if (empty($pagesstring)) {
            $pagesstring = '';
        }

        preg_match_all("#<a href=(.*?)>#", $this->code, $blogsurls);
        
        if ($blogsurls[1]) {
        	foreach ($blogsurls[1] as $blogurl) {
                if (strstr($blogurl, $this->dbobj->url) == false && strstr($blogurl, 'blogspot.com') != false) {
                	
	                // Skip if N.bp.blogspot.com
	                if (preg_match("/\d+\.bp\.blogspot/", $blogurl, $match)) {
	                    continue;
	                }
	                
                    $cleanlink = str_replace("'", "", str_replace('"', '', $blogurl));
                    $spacepos = strpos($cleanlink, ' ', 7);
                    $quotepos = strpos($cleanlink, '/', 7);
                    if($spacepos != false){
                        $cleanlink = substr($cleanlink, 0, $spacepos);
                    }
                    if($quotepos != false){
                        $cleanlink = substr($cleanlink, 0, $quotepos);
                    }
                    $cleanlink = str_replace('http://www.', 'http://', $cleanlink);
                    
                    
                    // Only a query per blogspot
                    $cleanblogurl[$cleanlink]['url'] = rtrim($cleanlink, '/').'/';
                    $cleanblogurl[$cleanlink]['name'] = str_replace('http://', '', str_replace('.blogspot.com', '', $cleanlink));
                }
        	}
        }
        
        // It's better to iterate again than to query DB again
        if (!empty($cleanblogurl)) {
        	foreach ($cleanblogurl as $cleanblog) {
        		
                // Only if the link was not already added
                if (!blogExists($cleanblog['name'], $cleanblog['url'])) {
                    $newlink = new Blog(false, $cleanblog['name'], $cleanblog['url']);
                    $newlink->insert();
                }
            }
        }
    }


    /**
     * Simple html clean to improve performance when parsing entries
     */
    public function domClean() {

        $this->code = preg_replace("/<link(.*?)>/", "", $this->code);
        $this->code = preg_replace("/\n/", " ", $this->code);
        $this->code = preg_replace("/<style(.*?)style>/", "", $this->code);
        $this->code = preg_replace("/style=\'(.*?)\'/", "", $this->code);
        $this->code = preg_replace("/style=\"(.*?)\"/", "", $this->code);
        $this->code = preg_replace("/<!--(.*?)-->/", "", $this->code);
        $this->code = preg_replace("/<script(.*?)script>/", "", $this->code);
        //$this->code = preg_replace("/<head(.*?)head>/", "", $this->code);
    }


    /**
     * Split the blog code in entries code
     */
    private function explodeEntries() {

        $entries = explode('<h3', $this->code);
        unset($entries[0]);

        foreach($entries as $key=>$entry){
            $entries[$key] = '<h3'.$entries[$key];
        }

        $string = implode('|||', $entries);
        $entries = explode('|||', $string);

        return $entries;
    }


    /**
     * Marks the blog as visited
     */
    public function markAsVisited() {
        $this->dbobj->timevisited = time();
        $this->update();
    }
    
}

?>